/*
 * Hacky baud rate generator to divide a 50MHz clock into a 115200 baud
 * rx/tx pair where the rx clcken oversamples by 16x.
 */
module baud_rate_gen #(
    parameter integer CLK_FREQ   = 50000000,
    parameter integer BAUDRATE   = 115200,
    parameter integer OVERSAMPLE = 16
) (
    input  wire sys_clk,
    input  wire rst_n,
    input  wire rxclk_gen_ena,
    input  wire txclk_gen_ena,
    output wire rxclk_en,
    output wire txclk_en
);

  localparam integer RxAccMax = CLK_FREQ / (BAUDRATE * OVERSAMPLE);
  localparam integer TxAccMax = CLK_FREQ / BAUDRATE;
  localparam integer RxAccWidth = $clog2(RxAccMax);
  localparam integer TxAccWidth = $clog2(TxAccMax);
  reg [RxAccWidth - 1:0] rx_acc = 0;
  reg [TxAccWidth - 1:0] tx_acc = 0;

  assign rxclk_en = rx_acc == RxAccMax[RxAccWidth-1:0] - 1;
  assign txclk_en = tx_acc == TxAccMax[TxAccWidth-1:0] - 1;

  always @(posedge sys_clk, negedge rst_n) begin
    if (~rst_n) rx_acc <= 0;
    else if (~rxclk_gen_ena) rx_acc <= 0;
    else if (rx_acc == RxAccMax[RxAccWidth-1:0] - 1) rx_acc <= 0;
    else rx_acc <= rx_acc + 1'b1;
  end

  always @(posedge sys_clk, negedge rst_n) begin
    if (~rst_n) tx_acc <= 0;
    else if (~txclk_gen_ena) tx_acc <= 0;
    else if (tx_acc == TxAccMax[TxAccWidth-1:0] - 1) tx_acc <= 0;
    else tx_acc <= tx_acc + 1'b1;
  end

endmodule
